package Orm.dbutils;

import Orm.jdbc.connectorPool.JDBCUtils;
import Orm.jdbc.ormdiy.City;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import java.sql.SQLException;

/**
 * 该类简单化了SQL查询，它与ResultSetHandler组合在一起使用可以完成大部分的数据库操作，能够大大减少编码量
 */
public class QueryRunnerStudy {
    public static void main(String[] args) throws SQLException {
        updateStudy();
    }

    /**
     *
     * @throws SQLException
     */
    public static void queryStudy() throws SQLException {
        DbUtils.loadDriver("com.mysql.cj.jdbc.Driver");
        QueryRunner runner = new QueryRunner(JDBCUtils.dataSource);
        City city = (City) runner.query("select * from city limit 1", new BeanHandler<City>(City.class));
        System.out.println(city);
        City city1 = (City) runner.query("select * from city where id=?", new BeanHandler<City>(City.class),4079);
        System.out.println(city1);
    }

    /**
     * 批量更新
     */
    public static void batchStudy() throws SQLException {
        DbUtils.loadDriver("com.mysql.cj.jdbc.Driver");
        QueryRunner runner = new QueryRunner(JDBCUtils.dataSource);
        String sql = "update city set name = 'YanKing' where id = ? ";
        Integer[][] params= new Integer[2][1];
        params[0][0] = 4080;
        params[1][0] = 4081;
        int[] res = runner.batch(sql,params);
        for(int n:res){
            System.out.println(n);
        }

    }

    /**
     *更新操作
     */
    public static void updateStudy() throws SQLException {
        DbUtils.loadDriver("com.mysql.cj.jdbc.Driver");
        QueryRunner runner = new QueryRunner(JDBCUtils.dataSource);
        String sql = "update city set name = 'YanQuque' where id = ? ";
        int resNum = runner.update(sql,4081);
        System.out.println(resNum);
    }
}
